package com.itic.appbase.applications.openoffice;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.itic.appbase.framework.utils.CommandHelper;
import com.itic.appbase.framework.utils.configuration.PropertyHelper;

/**
 * office转PDF类
 * <p>Company: itic</p>
 * @author: bianyuwu
 * @date: 2015年5月8日 上午9:18:03
 * @version: V1.0
 */
public class OpenOffice2PDF {

    private static final Logger log = LoggerFactory
            .getLogger(OpenOffice2PDF.class);
    
    private OpenOffice2PDF() {
    }

    /**
     * office转pdf.
     * 
     * @param sourceFile office文件地址
     * @param destFile 目标文件地址
     * @return int 操作成功与否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置错误; 如果返回 0,则表示操作成功; 返回1, 则表示转换失败
     * @throws InterruptedException
     */
    public static int office2PDF(String sourceFile, String destFile){
        try {
            log.debug("文件转换为PDF,[参数]SOURCEFile: " + sourceFile + "destFile: "
                    + destFile);
            File inputFile = new File(sourceFile);
            if (!inputFile.exists()) {
                return -1;// 找不到源文件, 则返回-1
            }
            // 如果目标路径不存在, 则新建该路径
            File outputFile = new File(destFile);
            if (outputFile.exists()){
                    return 0;
            }
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            } 
            // 连接服务
            OpenOfficeConnection connection = OpenOfficeServer.getConnection();
            connection.connect();
            // convert
            DocumentConverter converter = new OpenOfficeDocumentConverter(
                    connection);
            
            if (isTxt(inputFile)) {
                File odtFile = isWindows(inputFile);
                converter.convert(odtFile, outputFile);
            } else {
                converter.convert(inputFile, outputFile);
            }
            connection.disconnect();
            return 0;
        } catch (ConnectException e) {
            log.error("openoffice 连接失败！",e);
        } catch (IOException e) {
            log.error("文件格式转换失败",e);
        } catch (InterruptedException e) {
            log.error("文件转换失败",e);
            return 1;
        }
        return 1;
    }
    
    
    /**
     *  如果windows系统直接复制目标文件到odt文件
     *  如果是linux系统则进行编码转换到odt文件.
     *  
     * @param inputFile
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    private static File isWindows(File inputFile) throws IOException, InterruptedException{
        File odtFile = null;
        String prefix = inputFile.getAbsolutePath().substring(0,
                inputFile.getAbsolutePath().lastIndexOf("."));
        odtFile = new File(prefix + ".odt");
        if (System.getProperty("os.name").contains("Windows")) {
            copyFile(inputFile, odtFile);
        } else {
            toOdtFile(inputFile.getAbsolutePath(), prefix);
        }
        return odtFile;
    }

    /**
     * 复制文件 .
     * 
     * @param sourceFile 源文件
     * @param targetFile 目标文件
     * @throws IOException
     * @return void
     * @throws IOException
     */
    private static void copyFile(File sourceFile, File targetFile)
            throws IOException {
        FileInputStream input = new FileInputStream(sourceFile);
        BufferedInputStream inBuff = new BufferedInputStream(input);
        // 新建文件输出流并对它进行缓冲
        FileOutputStream output = new FileOutputStream(targetFile);
        BufferedOutputStream outBuff = new BufferedOutputStream(output);
        // 缓冲数组
        byte[] b = new byte[1024 * 5];
        int len;
        while ((len = inBuff.read(b)) != -1) {
            outBuff.write(b, 0, len);
        }
        // 刷新此缓冲的输出流
        outBuff.flush();
        // 关闭流
        inBuff.close();
        outBuff.close();
        output.close();
        input.close();
    }

    /**
     * 判断是否是TXT.
     *  
     * @param file 要判断的文件
     * @throws IOException
     * @return boolean
     * @throws IOException
     */
    private static boolean isTxt(File file) throws IOException {
        String fileName = file.getName();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        return ".txt".equals(suffix) || ".TXT".equals(suffix);
    }

    /**
     * 文件编码转换.
     * 
     * @param source 源文件件地址
     * @param target 目标文件地址
     * @throws IOException
     * @throws InterruptedException
     * @return result
     */
    private static boolean toOdtFile(String source, String target)
            throws IOException, InterruptedException {
        String command = "";
        if (System.getProperty("os.name").contains("Windows")) {
            command = "iconv -f gb2312 -t "
                    + PropertyHelper.getString("windows.server.encode") + " "
                    + source + " -c -s -o " + target + ".odt";
        } else {
            command = "iconv -f gb2312 -t "
                    + PropertyHelper.getString("linux.server.encode") + " "
                    + source + " -c -s -o " + target + ".odt";
        }
        log.debug("command:[" + command + "]");
        return CommandHelper.runCommand(command) == 0;
    }

}
